package com.xyh.transaction.service.imp;

import com.xyh.transaction.common.Constant;
import com.xyh.transaction.common.Current;
import com.xyh.transaction.common.ImageType;
import com.xyh.transaction.entity.Cart;
import com.xyh.transaction.entity.Goods;
import com.xyh.transaction.entity.Image;
import com.xyh.transaction.entity.dto.cart.CartDto;
import com.xyh.transaction.entity.vo.CartVo;
import com.xyh.transaction.mapper.CartMapper;
import com.xyh.transaction.mapper.GoodsMapper;
import com.xyh.transaction.mapper.ImageMapper;
import com.xyh.transaction.mapper.UserMapper;
import com.xyh.transaction.service.CartService;
import com.xyh.transaction.utils.ImageUtils;
import com.xyh.transaction.utils.MappingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ImageUtils imageUtils;

    @Override
    public List<CartVo> getCartList() {

        Integer userId = Current.getCurrentUser().getUser().getId();

        List<Cart> cartList = cartMapper.findByUserId(userId);

        return cartList.stream().map(cart -> {
            CartVo cartVo = new CartVo();

            cartVo.setId(cart.getId());
            cartVo.setCount(cart.getCount());
            cartVo.setSelected(cart.getSelected() == 1);
            cartVo.setGoodsId(cart.getGoodsId());

            Goods goods = goodsMapper.findById(cart.getGoodsId());
            cartVo.setName(goods.getName());
            cartVo.setPrice(goods.getPrice());
            List<String> images = imageMapper.findByRelatedId(goods.getId(), ImageType.GOODS).stream().map(image -> imageUtils.buildImageUrl(image.getUrl()))
                    .collect(Collectors.toList());
            cartVo.setPicture(images.isEmpty() ? Constant.DEFAULT_GOODS : images.get(0));
            cartVo.setGoodsCreateBy(goods.getCreateBy());
            cartVo.setGoodsCreateByName(userMapper.findById(goods.getCreateBy()).getUsername());
            cartVo.setGoodsStock(goods.getStock());
            return cartVo;
        }).collect(Collectors.toList());
    }

    @Override
    public void addCart(CartDto addCartDto) {
        // 记录；addCartDto中的selected(boolean)会被映射为cart selected（int）  ture -> 1  false -> 0
        Cart cart = MappingUtil.mapObject(addCartDto, Cart.class);
        Integer userId = Current.getCurrentUser().getUser().getId();

        Cart hasCart = cartMapper.findByUserIdAndGoods(userId, cart.getGoodsId());
        if (hasCart != null) {
            hasCart.setCount(hasCart.getCount() + cart.getCount());
            hasCart.setUpdateTime(LocalDateTime.now());
            cartMapper.update(hasCart);
            return;
        }

        cart.setUserId(userId);
        cart.setCreateBy(userId);
        cart.setUpdateBy(userId);
        cart.setCreateTime(LocalDateTime.now());
        cart.setUpdateTime(LocalDateTime.now());

        cartMapper.insert(cart);
    }

    @Override
    public void mergeCart(List<CartDto> cartDtoList) {
        for (CartDto cartDto : cartDtoList) {
            // 判断商品是否是数据库存在的
            if (goodsMapper.findById(cartDto.getGoodsId()) == null){
                continue;
            }
            // 实际就是添加购物车逻辑
            addCart(cartDto);
        }
    }

    @Override
    public void updateCartBatch(List<CartDto> cartDtos) {
        for (CartDto cartDto : cartDtos) {
            Cart cart = MappingUtil.mapObject(cartDto, Cart.class);
            cart.setUpdateTime(LocalDateTime.now());
            cartMapper.update(cart);
        }
    }

    @Override
    public void deleteCart(List<Integer> ids) {
        cartMapper.deleteBatchById(ids);
    }
}
